﻿
// StoreSCPDlg.cpp: 实现文件
//

#include "pch.h"
#include "framework.h"
#include "StoreSCP.h"
#include "StoreSCPDlg.h"
#include "afxdialogex.h"
#include "Utilities.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif


// 用于应用程序“关于”菜单项的 CAboutDlg 对话框

class CAboutDlg : public CDialogEx
{
public:
	CAboutDlg();

// 对话框数据
#ifdef AFX_DESIGN_TIME
	enum { IDD = IDD_ABOUTBOX };
#endif

	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV 支持

// 实现
protected:
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialogEx(IDD_ABOUTBOX)
{
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialogEx::DoDataExchange(pDX);
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx)
END_MESSAGE_MAP()


// CStoreSCPDlg 对话框
static int CALLBACK BrowseCallbackProc(HWND hWnd, UINT uMsg, LPARAM, LPARAM lpData)
{
	if (uMsg == BFFM_INITIALIZED)
	{
		CTreeCtrl   treePath;
		HTREEITEM   hItemSel;
		::SendMessage(hWnd, BFFM_SETSELECTION, TRUE, lpData);
		treePath.SubclassWindow(::GetDlgItem(hWnd, 0x3741));
		hItemSel = treePath.GetSelectedItem();
		treePath.Expand(hItemSel, TVE_COLLAPSE);
		treePath.UnsubclassWindow();
	}
	return 0;
}


CStoreSCPDlg::CStoreSCPDlg(CWnd* pParent /*=nullptr*/)
	: CDialogEx(IDD_STORESCP_DIALOG, pParent)
	, m_port(3000)
	, m_aet(_T("xg-storescp"))
	, m_rootDir(_T(""))
{
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
	m_brBlack.CreateSolidBrush(RGB(0, 0, 0));
}

void CStoreSCPDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialogEx::DoDataExchange(pDX);
	DDX_Text(pDX, IDC_EDIT_PORT, m_port);
	DDX_Text(pDX, IDC_EDIT_AET, m_aet);
	DDX_Text(pDX, IDC_EDIT_ROOT_DIR, m_rootDir);
	DDX_Control(pDX, IDC_COMBO_LL, m_cmbLL);
	DDX_Control(pDX, IDC_EDIT_LOG, m_log);
}

BEGIN_MESSAGE_MAP(CStoreSCPDlg, CDialogEx)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_WM_CTLCOLOR()
	ON_BN_CLICKED(IDC_BUTTON_START, &CStoreSCPDlg::OnBnClickedButtonStart)
	ON_BN_CLICKED(IDC_BUTTON_DIR, &CStoreSCPDlg::OnBnClickedButtonDir)
	ON_BN_CLICKED(IDC_BUTTON_DEFDIR, &CStoreSCPDlg::OnBnClickedButtonDefdir)
	ON_BN_CLICKED(IDC_BUTTON_CLEAR_LOG, &CStoreSCPDlg::OnBnClickedButtonClearLog)
	ON_CBN_SELCHANGE(IDC_COMBO_LL, &CStoreSCPDlg::OnSelchangeComboLl)
	ON_MESSAGE(UM_ADD_LOG, &CStoreSCPDlg::OnAddLog)
	ON_MESSAGE(UM_SERVER_START, &CStoreSCPDlg::OnServerStart)
	ON_MESSAGE(UM_SERVER_STOP, &CStoreSCPDlg::OnServerStop)
	ON_WM_SIZE()
	ON_WM_GETMINMAXINFO()
	ON_WM_DESTROY()
END_MESSAGE_MAP()


// CStoreSCPDlg 消息处理程序

BOOL CStoreSCPDlg::OnInitDialog()
{
	CDialogEx::OnInitDialog();

	// 将“关于...”菜单项添加到系统菜单中。

	// IDM_ABOUTBOX 必须在系统命令范围内。
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != nullptr)
	{
		BOOL bNameValid;
		CString strAboutMenu;
		bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
		ASSERT(bNameValid);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// 设置此对话框的图标。  当应用程序主窗口不是对话框时，框架将自动
	//  执行此操作
	SetIcon(m_hIcon, TRUE);			// 设置大图标
	SetIcon(m_hIcon, FALSE);		// 设置小图标

	// TODO: 在此添加额外的初始化代码
	CString msg;
	msg.Format(_T("程序启动, AET:%s, 端口:%d"), m_aet, m_port);
	addLog(msg);
	m_rootDir = GetAppPath().c_str();
	m_rootDir += _T("RecvFiles");


	m_cmbLL.AddString(_T("调试"));
	m_cmbLL.AddString(_T("通知"));
	m_cmbLL.AddString(_T("警告"));
	m_cmbLL.AddString(_T("错误"));
	m_cmbLL.SetCurSel(1);

	m_storeSCP.Init(std::string(m_aet), m_port, this->m_hWnd, std::string(m_rootDir));
	m_storeSCP.SetLogLevel(1);

	Arrange();

	UpdateData(FALSE);

	return TRUE;  // 除非将焦点设置到控件，否则返回 TRUE
}

void CStoreSCPDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialogEx::OnSysCommand(nID, lParam);
	}
}

// 如果向对话框添加最小化按钮，则需要下面的代码
//  来绘制该图标。  对于使用文档/视图模型的 MFC 应用程序，
//  这将由框架自动完成。

void CStoreSCPDlg::OnPaint()
{
	if (IsIconic())
	{
		CPaintDC dc(this); // 用于绘制的设备上下文

		SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);

		// 使图标在工作区矩形中居中
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// 绘制图标
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialogEx::OnPaint();
	}
}

//当用户拖动最小化窗口时系统调用此函数取得光标
//显示。
HCURSOR CStoreSCPDlg::OnQueryDragIcon()
{
	return static_cast<HCURSOR>(m_hIcon);
}



void CStoreSCPDlg::OnBnClickedButtonStart()
{
	// TODO: 在此添加控件通知处理程序代码
	if (m_storeSCP.GetState() == 0) {
		m_storeSCP.Start();
	}
	else {
		m_storeSCP.Stop();
	}
}


void CStoreSCPDlg::OnBnClickedButtonDir()
{
	// TODO: 在此添加控件通知处理程序代码
	TCHAR           szFolderPath[MAX_PATH] = { 0 };

	BROWSEINFO      sInfo;
	::ZeroMemory(&sInfo, sizeof(BROWSEINFO));
	sInfo.pidlRoot = 0;
	sInfo.lpszTitle = _T("选择归档目录：");
	sInfo.ulFlags = BIF_BROWSEFORCOMPUTER | BIF_NEWDIALOGSTYLE | BIF_RETURNONLYFSDIRS;
	sInfo.lpfn = BrowseCallbackProc;
	sInfo.lParam = (LPARAM)(LPCTSTR)m_rootDir;

	// 显示文件夹选择对话框  
	LPITEMIDLIST lpidlBrowse = ::SHBrowseForFolder(&sInfo);
	if (lpidlBrowse != NULL)
	{
		if (::SHGetPathFromIDList(lpidlBrowse, szFolderPath))
		{
			m_rootDir = szFolderPath;
			UpdateData(FALSE);
		}

		::CoTaskMemFree(lpidlBrowse);
	}
}


void CStoreSCPDlg::OnBnClickedButtonDefdir()
{
	m_rootDir = GetAppPath().c_str();
	m_rootDir += _T("RecvFiles");
	UpdateData(FALSE);
}


void CStoreSCPDlg::OnBnClickedButtonClearLog()
{
	// TODO: 在此添加控件通知处理程序代码
	m_log.SetSel(0, -1);
	m_log.ReplaceSel(_T(""), FALSE);
}



LRESULT CStoreSCPDlg::OnAddLog(WPARAM wParam, LPARAM lParam)
{
	CString logStr = (LPCTSTR)wParam;

	if (m_log.m_hWnd && IsWindow(m_log.m_hWnd))
	{
		int nLmt = m_log.GetLimitText();
		int nTextLength = m_log.GetWindowTextLength();
		if ((int)(nTextLength + logStr.GetLength()) >= nLmt)
		{
			int nPos = m_log.LineIndex(100);
			m_log.SetSel(0, nPos);
			m_log.ReplaceSel(_T(""), FALSE);
		}

		m_log.SetSel(nTextLength, nTextLength);
		m_log.ReplaceSel(logStr);
		m_log.PostMessage(EM_SETSEL, -1, -1);
	}

	return 0;
}

LRESULT CStoreSCPDlg::OnServerStart(WPARAM wParam, LPARAM lParam)
{
	//CString msg;
	//msg.Format(_T("服务已启动,监听端口[%d]"), m_port);
	//addLog(msg);
	GetDlgItem(IDC_BUTTON_START)->SetWindowText(_T("停止服务"));
	return 0;
}

LRESULT CStoreSCPDlg::OnServerStop(WPARAM wParam, LPARAM lParam)
{
	//addLog(_T("服务已停止."));
	GetDlgItem(IDC_BUTTON_START)->SetWindowText(_T("启动服务"));
	return 0;
}

void CStoreSCPDlg::addLog(CString str)
{
	std::string timeStr = GetLogTimeStr();
	CString logStr;
	logStr.Format(_T("[%s][App] %s\r\n"), timeStr.c_str(), str);
	::SendMessage(this->m_hWnd, UM_ADD_LOG, (WPARAM)(LPCTSTR)logStr, 0);
}

void CStoreSCPDlg::Arrange()
{
	CRect rc;
	GetClientRect(&rc);

	CRect rcLL;
	m_cmbLL.GetWindowRect(&rcLL);
	ScreenToClient(&rcLL);
	int y = rcLL.bottom + 10;
	m_log.MoveWindow(6, y, rc.Width() - 12, rc.bottom - y - 6);
}

HBRUSH CStoreSCPDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{
	HBRUSH hbr = CDialogEx::OnCtlColor(pDC, pWnd, nCtlColor);

	// TODO:  在此更改 DC 的任何特性
	if (pWnd && pWnd->m_hWnd == m_log.GetSafeHwnd())
	{
		pDC->SetBkColor(0);
		pDC->SetTextColor(RGB(220, 220, 220));
		return m_brBlack;
	}

	// TODO:  如果默认的不是所需画笔，则返回另一个画笔
	return hbr;
}


void CStoreSCPDlg::OnSelchangeComboLl()
{
	// TODO: 在此添加控件通知处理程序代码
	int idx = m_cmbLL.GetCurSel();
	if (idx == -1) return;
	m_storeSCP.SetLogLevel(idx);
}


void CStoreSCPDlg::OnSize(UINT nType, int cx, int cy)
{
	CDialogEx::OnSize(nType, cx, cy);

	// TODO: 在此处添加消息处理程序代码
	if (::IsWindow(m_log.m_hWnd) && nType != SIZE_MINIMIZED) {
		Arrange();
	}
}


void CStoreSCPDlg::OnGetMinMaxInfo(MINMAXINFO* lpMMI)
{
	// TODO: 在此添加消息处理程序代码和/或调用默认值
	lpMMI->ptMinTrackSize.x = 600;			//最小宽度
	lpMMI->ptMinTrackSize.y = 500;			//最小高度
	CDialogEx::OnGetMinMaxInfo(lpMMI);
}


void CStoreSCPDlg::OnDestroy()
{
	if (m_storeSCP.GetState() == 1) {
		m_storeSCP.Stop();
	}

	CDialogEx::OnDestroy();

	// TODO: 在此处添加消息处理程序代码
}
